//
//  MNDInfoDisclosureViewController.m
//  minidai
//
//  Created by 容贤郁 on 2018/3/13.
//  Copyright © 2018年 迷你金服. All rights reserved.
//

#import "MNDInfoDisclosureViewController.h"
#import "SYWebLoadingProgress.h"

@interface MNDInfoDisclosureViewController () <UIWebViewDelegate>

@property (nonatomic, strong) UIWebView *webView;
@property (strong, nonatomic) UIButton *closeButton;

@property (strong, nonatomic) SYWebLoadingProgress *webLoadingProgress;

@end

@implementation MNDInfoDisclosureViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"信息披露";
    
    [self initialWebView];
    
    [self initialBackButton];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initialWebView {
    self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    self.webView.backgroundColor = kColorBackground;
    self.webView.scrollView.bounces = NO;
    self.webView.scalesPageToFit = YES;
    
    self.webView.delegate = self;
    NSURL *url = [NSURL URLWithString:kInformationDisclosure];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60.0];
    [self.webView loadRequest:request];

    [self.view addSubview:self.webView];
    
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.view beginLoading];
}

- (void)initialBackButton {
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    
    self.closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.closeButton setTitle:@"关闭" forState:UIControlStateNormal];
    self.closeButton.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [self.closeButton setTitleColor:[UIColor colorWithRed:57/255.0 green:66/255.0 blue:64/255.0 alpha:1.0] forState:UIControlStateNormal];
    [self.closeButton addTarget:self action:@selector(closeAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.closeButton setFrame:CGRectMake(0, 0, 40, 30)];
    [self.closeButton setHidden:YES];
    
    UIBarButtonItem *closeItem = [[UIBarButtonItem alloc] initWithCustomView:self.closeButton];
    //    [closeItem setTintColor: [UIColor colorWithRed:57/255.0 green:66/255.0 blue:64/255.0 alpha:1.0]];
    
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItems = @[backBarButtonItem, closeItem];;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem, closeItem];
    }
}

- (void)backAction:(id)sender {
    if (self.webView.canGoBack) {
        [self.closeButton setHidden:NO];
        [self.webView goBack];
    } else {
        if (self.presentingViewController) {
            [self dismissViewControllerAnimated:YES completion:NULL];
        } else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

- (void)closeAction:(id)sender {
    if (self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:NULL];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - UIWebView Delegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    
    [self.webLoadingProgress startProgressAnimation];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    //    取消长按webView上的链接弹出actionSheet的问题
    [webView stringByEvaluatingJavaScriptFromString: @"document.documentElement.style.webkitUserSelect='none';"];
    if ([webView.request.URL.absoluteString containsString:kCustomerServiceURLStr]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('chat-view-window-header-back')[0].style.display='none';"];
            self.title = @"在线客服";
        });
    } else {
        self.title = @"信息披露";
    }
    [self.webLoadingProgress completedProgressAnimation];
    [self.view endLoading];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    [self.webLoadingProgress completedProgressAnimation];
    if (error.code == -999) {
        return;
    }
    
    if (error.code == 102 || error.code == -102) {
        return;
    }
    
    [NetworkProgressHUD showHudNetworkError:error];
    WeakSelf(self);
    SYBlankPageType blankType = [weakself.view blankPageTypeWithError:error];
    [self.view configBlankPage:blankType hasData:NO reloadButtonBlock:^(id sender) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakself.webView reload];
            //            [weakself.view beginLoading];
        });
        
    }];
}

- (SYWebLoadingProgress *)webLoadingProgress {
    if (!_webLoadingProgress) {
        _webLoadingProgress = [[SYWebLoadingProgress alloc] init];
        _webLoadingProgress.progressColor = kColorBlue;
        _webLoadingProgress.progressStyle = LoadingPregressType_Noraml;
    }
    
    if ([self.navigationController.navigationBar isHidden]) {
        _webLoadingProgress.frame = CGRectMake(0, 20, kScreenWidth, 2);
        
    } else {
        CGFloat yPosition = 64.0;
        if (kScreenHeight >= 812) {
            yPosition = 88;
        }
        _webLoadingProgress.frame = CGRectMake(0, yPosition, kScreenWidth, 2);
        //        [self.view.layer insertSublayer:_webLoadingProgress atIndex:0];
    }
    [self.webView.layer addSublayer:_webLoadingProgress];
    
    return _webLoadingProgress;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
